#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPWeb.
#    COOPWeb is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPWeb is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPWeb.  If not, see <http://www.gnu.org/licenses/>.

import os, pickle
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopweb/djangoproject/include', '/opt/coopweb/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopweb/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings



class DynForm(forms.Form):    
    """Dynamic form that allows the user to change and then verify the data that was parsed"""
    def setFields(self, kwds):
        """Set the fields in the form"""
        keys = kwds.keys()
        keys.sort()
        for k in keys:
            self.fields[k] = kwds[k]            
    def setData(self, kwds):
        """Set the data to include in the form"""
        self.is_bound = True 
        keys = kwds.keys()
        keys.sort()
        for k in keys:
            self.data[k] = kwds[k]
    def validate(self, post):
        """Validate the contents of the form"""
        for name,field in self.fields.items():
            try:
                field.clean(post[name])
            except ValidationError, e:
                self.errors[name] = e.messages
    class Media:  #Should not affect any non-Map forms
        js=("http://localhost/openlayers/OpenLayers.js",)


def WalkDirectory(Root, Directories = [], Files = {}):
    """Root=the root directory that the walk starts on, or a subdirectory under the root that was recursively called
       Directories=An Empty List to Start, the full path of each directory under Root, including Root Itself
       Files=An Empty Dictionary to Start, the name of each file, with a full path.  The value of each file is the
             file last modify date"""
    for filename in os.listdir(Root):
        if(os.path.isdir(Root + filename)):
            WalkDirectory(Root + filename + '/', Directories, Files)
            Directories.append(Root + filename + '/')
        else:
            Files[Root + filename] = os.path.getmtime(Root + filename)
    return Directories, Files

def CreateDirectories(Directories):
    for directory in Directories:
        os.system("sudo -u apachescript sudo mkdir " + directory)
            

def GetRemoteFile(FileLocation, PickleIndicator=False):
    os.system("sudo -u apachescript sudo wget -O " + djangoproject.settings.COOPWebTemporaryFileName + 
              " http://" + djangoproject.settings.COOPWebServerIPAddress + '/' + FileLocation)
    File=open(djangoproject.settings.COOPWebTemporaryFileName, 'rb')
    if(PickleIndicator):
        Results=pickle.load(File)
    else:
        ResultsList=[]
        for char in File.read():
            ResultsList.append(char)
        Results=''.join(ResultsList)
    File.close()
    os.system("sudo -u apachescript sudo rm " + djangoproject.settings.COOPWebTemporaryFileName)
    return Results

